package com.cropflow.service;

import com.cropflow.entity.MaintenanceRecord;
import com.cropflow.entity.Vehicle;
import com.cropflow.repository.MaintenanceRecordRepository;
import com.cropflow.repository.VehicleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class VehicleService {
    
    @Autowired
    private VehicleRepository vehicleRepository;
    
    @Autowired
    private MaintenanceRecordRepository maintenanceRecordRepository;
    
    // 基础CRUD操作
    public List<Vehicle> getAllVehicles() {
        return vehicleRepository.findAll();
    }
    
    public Vehicle getVehicleById(Long id) {
        return vehicleRepository.findById(id).orElse(null);
    }
    
    public Vehicle saveVehicle(Vehicle vehicle) {
        vehicle.setLastUpdateTime(LocalDateTime.now());
        return vehicleRepository.save(vehicle);
    }
    
    public void deleteVehicle(Long id) {
        vehicleRepository.deleteById(id);
    }
    
    // 设备状态监控
    public Map<String, Object> getVehicleStatus(Long vehicleId) {
        Vehicle vehicle = getVehicleById(vehicleId);
        Map<String, Object> status = new HashMap<>();
        
        if (vehicle != null) {
            status.put("id", vehicle.getId());
            status.put("name", vehicle.getName());
            status.put("status", vehicle.getStatus());
            status.put("batteryLevel", vehicle.getBatteryLevel());
            status.put("latitude", vehicle.getLatitude());
            status.put("longitude", vehicle.getLongitude());
            status.put("lastUpdateTime", vehicle.getLastUpdateTime());
        }
        
        return status;
    }
    
    public List<Vehicle> getAvailableVehicles() {
        return vehicleRepository.findByStatus(Vehicle.VehicleStatus.IDLE);
    }
    
    public List<Vehicle> getLowBatteryVehicles() {
        return vehicleRepository.findLowBatteryVehicles(20.0); // 电量低于20%
    }
    
    public List<Vehicle> getVehiclesNeedingMaintenance() {
        return vehicleRepository.findVehiclesNeedingMaintenance(LocalDateTime.now());
    }
    
    // 远程控制功能
    public boolean sendControlCommand(Long vehicleId, String command) {
        Vehicle vehicle = getVehicleById(vehicleId);
        if (vehicle == null) {
            return false;
        }
        
        try {
            // 模拟发送控制指令到设备
            System.out.println("Sending command to vehicle " + vehicleId + ": " + command);
            
            // 根据指令更新设备状态
            switch (command.toLowerCase()) {
                case "start":
                    vehicle.setStatus(Vehicle.VehicleStatus.WORKING);
                    break;
                case "stop":
                    vehicle.setStatus(Vehicle.VehicleStatus.IDLE);
                    break;
                case "return":
                    vehicle.setStatus(Vehicle.VehicleStatus.IDLE);
                    break;
                case "maintenance":
                    vehicle.setStatus(Vehicle.VehicleStatus.MAINTENANCE);
                    break;
            }
            
            vehicleRepository.save(vehicle);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    // 设备配置管理
    public boolean updateVehicleConfig(Long vehicleId, Map<String, Object> config) {
        Vehicle vehicle = getVehicleById(vehicleId);
        if (vehicle == null) {
            return false;
        }
        
        if (config.containsKey("workingMode")) {
            vehicle.setWorkingMode((String) config.get("workingMode"));
        }
        if (config.containsKey("maxSpeed")) {
            vehicle.setMaxSpeed((Double) config.get("maxSpeed"));
        }
        if (config.containsKey("sensorConfig")) {
            vehicle.setSensorConfig((String) config.get("sensorConfig"));
        }
        
        vehicleRepository.save(vehicle);
        return true;
    }
    
    // 维护记录管理
    public List<MaintenanceRecord> getMaintenanceRecords(Long vehicleId) {
        Vehicle vehicle = getVehicleById(vehicleId);
        return maintenanceRecordRepository.findByVehicleOrderByStartTimeDesc(vehicle);
    }
    
    public MaintenanceRecord createMaintenanceRecord(MaintenanceRecord record) {
        return maintenanceRecordRepository.save(record);
    }
    
    public MaintenanceRecord completeMaintenanceRecord(Long recordId, String result, Double cost) {
        MaintenanceRecord record = maintenanceRecordRepository.findById(recordId).orElse(null);
        if (record != null) {
            record.setEndTime(LocalDateTime.now());
            record.setResult(result);
            record.setCost(cost);
            
            // 更新车辆维护信息
            Vehicle vehicle = record.getVehicle();
            vehicle.setLastMaintenanceDate(LocalDateTime.now());
            vehicle.setNextMaintenanceDate(LocalDateTime.now().plusMonths(3)); // 3个月后下次维护
            vehicle.setStatus(Vehicle.VehicleStatus.IDLE);
            
            vehicleRepository.save(vehicle);
            return maintenanceRecordRepository.save(record);
        }
        return null;
    }
    
    // 实时位置更新
    public void updateVehicleLocation(Long vehicleId, Double latitude, Double longitude) {
        Vehicle vehicle = getVehicleById(vehicleId);
        if (vehicle != null) {
            vehicle.setLatitude(latitude);
            vehicle.setLongitude(longitude);
            vehicle.setLastUpdateTime(LocalDateTime.now());
            vehicleRepository.save(vehicle);
        }
    }
    
    // 电池电量更新
    public void updateBatteryLevel(Long vehicleId, Double batteryLevel) {
        Vehicle vehicle = getVehicleById(vehicleId);
        if (vehicle != null) {
            vehicle.setBatteryLevel(batteryLevel);
            vehicle.setLastUpdateTime(LocalDateTime.now());
            vehicleRepository.save(vehicle);
        }
    }
}